import java.util.ArrayList;
import java.util.List;

/**
 * @author tmh
 * @date 2024/10/13 21:50
 * @description
 */
public class TLCR181字符串中的单词反转 {
    public static void main(String[] args) {
        reverseMessage1("the sky is blue");
    }

    /**
     * 使用StringBuilder 预备知识：x个空格经过split(" ")会得到x-1的空串
     *
     * @param message
     * @return
     */
    public String reverseMessage(String message) {
        message = message.trim();
        String[] strings = message.split(" ");
        StringBuilder builder = new StringBuilder();
        for (int i = strings.length - 1; i >= 0; i--) {
            if ("".equals(strings[i])) {
                continue;
            }
            builder.append(strings[i]).append(" ");
        }
        //因为最后会多出来一个空格，所以需要进行去重
        return builder.toString().trim();
    }

    public static String reverseMessage1(String message) {
        message = message.trim();
        int len = message.length();
        int i = len - 1;
        int j = len - 1;
        StringBuilder builder = new StringBuilder();
        while (i >= 0) {
            //第二个循环和第三个循环都要有i>=0的条件，因为第一个单词结束之后i=-1，charAt(-1)会报错
            while (i >= 0 && message.charAt(i) != ' ') {
                i--;
            }
            builder.append(message.substring(i + 1, j + 1)).append(" ");
            //在来一个while循环处理多个空格的情况
            while (i >= 0 && message.charAt(i) == ' ') {
                i--;
            }
            //此时i指向另一个单词的末尾
            j = i;
        }
        return builder.toString().trim();
    }
}
